
import config from '@/request/baseUrl.js';
import { checkNetwork } from "@/request/common.js";

function request({method, url, data}, loading = true) {
	const token = uni.getStorageSync('TOKEN')
	return new Promise((resolve, reject) => {
		if (loading) {
			uni.showLoading({
				title: '加载中',
				mask: true
			});
		}
		uni.request({
			url: config.baseUrl + url,
			data,
			header: {
				Authorization: token ? "Bearer " + token : ''
			},
			timeout: 1000 * 60 * 5, // 超时时间
			method,
			success(res) {
				if (loading) uni.hideLoading();
				switch (res.statusCode) {
					case 200:
						if (res.data.code == 200 || res.data.code == 1002) {
							resolve(res.data)
						} else if (res.data.code == 401) {
							loginModel()
						} else {
							resolve(res.data)
							uni.showToast({
								title: res.data.msg || '服务器错误',
								icon: 'none',
								mask: true,
								duration: 1500
							})
						}
						break;
					case 401:
						loginModel();
						break;
					case 404:
						uni.showToast({
							title: '服务器错误',
							duration: 1500,
							icon: 'none'
						})
						resolve(false)
						break;
					case 500:
						uni.showToast({
							title: '服务器错误',
							duration: 1500,
							icon: 'error'
						})
						resolve(false)
						break;
					default:
						resolve(false)
						break;
				}
			},
			fail: async () => {
				if (loading) uni.hideLoading();
				const network = await checkNetwork(); // 检查网络
				if (network != 'none') {
					uni.showToast({
						title: '网络错误',
						duration: 1500,
						icon: 'none'
					})
				}
				resolve(false)
			}
		})
	})
}

let showLogin = false; // 是否已显示登录弹窗

// 登录弹窗
function loginModel() {
	if (showLogin) return;
	showLogin = true;
	const token = uni.getStorageSync('TOKEN')
	uni.stopPullDownRefresh();
	uni.showModal({
		title: '提示',
		content: token ? '登录已失效，请重新登录' : '您还未登录，请先登录',
		showCancel: true,
		success: ({ confirm }) => {
			if (confirm) {
				if (token)	uni.removeStorageSync('TOKEN');
				uni.navigateTo({
					url: '/pages/login/index'
				})
			}
		},
		complete: () => {
			showLogin = false;
		}
	})
}

export default request;
